#include "app_message.h"
#include "stdlib.h"
#include "cjson/cJSON.h"
#include "app_common.h"
#include "string.h"

char* app_message_charsToJson(char *data)
{
    // 1. 解析data
    int conn_type = data[0];
    int id_len = data[1];
    int msg_len = data[2];
    char id_str[id_len];
    char msg_str[msg_len];
    memcpy(id_str, data+3, id_len);
    memcpy(msg_str, data+3+id_len, msg_len);

    // 2. 将字符数组转换为hexstr
    char* id_hexstr = app_common_charsToHexstr(id_str, id_len);
    char* msg_hexstr = app_common_charsToHexstr(msg_str, msg_len);

    // 3. 将hexstr转换为json
    cJSON* root = cJSON_CreateObject();
    cJSON_AddNumberToObject(root, "conn_type", conn_type);
    cJSON_AddStringToObject(root, "id", id_hexstr);
    cJSON_AddStringToObject(root, "msg", msg_hexstr);
    char* data_json = cJSON_PrintUnformatted(root);

    // 4. 释放内存
    cJSON_Delete(root);
    free(id_hexstr);
    free(msg_hexstr);

    return data_json;
}

int app_message_jsonToChars(char *data_json ,char *data_buf,int buf_size)
{
    // 1.解析Json字符串
    cJSON* root = cJSON_Parse(data_json);
    int conn_type = cJSON_GetObjectItem(root, "conn_type")->valueint;
    char* id_hexstr = cJSON_GetObjectItem(root, "id")->valuestring;
    char* msg_hexstr = cJSON_GetObjectItem(root, "msg")->valuestring;

    // 2.将hexstr转换为字符数组
    // 2.1 获取id和msg的长度(字符长度非16进制长度)
    int id_len;
    int msg_len;
    char* id_str = app_common_hexstrToChars(id_hexstr, &id_len);
    char* msg_str = app_common_hexstrToChars(msg_hexstr, &msg_len);
    int chars_len = id_len + msg_len + 3; // 字符数组长度

    // 3.将Json字符串信息写入字符数组
    data_buf[0] = conn_type;
    data_buf[1] = id_len;
    data_buf[2] = msg_len;
    memcpy(data_buf+3, id_str, id_len);
    memcpy(data_buf+3+id_len, msg_str, msg_len);

    // 4.释放内存
    cJSON_Delete(root);
    free(id_str);
    free(msg_str); 

    // 5.返回字符数组长度
    return chars_len;
}


